<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;

class Handler extends ExceptionHandler
{
    private $code;
    private $status;
    private $msg;

    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<Throwable>>
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Throwable  $e
     * @return \Symfony\Component\HttpFoundation\Response
     *
     * @throws \Throwable
     */
    public function render($request, Throwable $e)
    {
        if ($e instanceof BaseException) {
            // 自定义的异常
            $this->code = $e->code;
            $this->status = $e->status;
            $this->msg = $e->msg;
        } else {
            if (config('app.debug')) {
                // 其他错误交给系统处理
                return parent::render($request, $e);
            }

            $this->code = 500;
            $this->status = 0;
            $this->msg = $e->getMessage();
        }

        $result = [
            'code' => $this->code,
            'status' => $this->status,
            'msg' => $this->msg,
            'data' => []
        ];

        return response()->json($result)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    }
}
